#!/bin/bash
set -e

SPEC_PRJNAME=${PRJ_BASENAME:-bizark_port_web}
PRJBASEDIR="$( cd "$( dirname "$(readlink -f ${BASH_SOURCE[0]})" )"/../ >/dev/null && pwd )"
PRJDIR="$( cd "$( dirname "$(readlink -f ${BASH_SOURCE[0]})" )"/ >/dev/null && pwd )"
PRJNAME=${SPEC_PRJNAME:-${PRJBASEDIR##*/}}
PRJPREFIX=${PRJNAME//_/-}
BUILDENV="${APP_ENV:-${1:-dev}}"
APPMOD="all"
APPDEBUG="${2:-debug}"
LOG_FILE="${LOG_FILE:-/dev/null}"

# waitterm
#   wait TERM/INT signal.
#   see: http://veithen.github.io/2014/11/16/sigterm-propagation.html
waitterm() {
	local PID
	# any process to block
	tail -f /dev/null &
	PID="$!"
	# setup trap, could do nothing, or just kill the blocker
	trap "kill -TERM ${PID}" TERM INT
	# wait for signal, ignore wait exit code
	wait "${PID}" || true
	# clear trap
	trap - TERM INT
	# wait blocker, ignore blocker exit code
	wait "${PID}" 2>/dev/null || true
}

# waittermpid "${PIDFILE}".
#   monitor process by pidfile && wait TERM/INT signal.
#   if the process disappeared, return 1, means exit with ERROR.
#   if TERM or INT signal received, return 0, means OK to exit.
waittermpid() {
	local PIDFILE PID do_run error
	PIDFILE="${1?}"
	do_run=true
	error=0
	trap "do_run=false" TERM INT
	while "${do_run}" ; do
		PID="$(cat "${PIDFILE}")"
		if ! ps -p "${PID}" >/dev/null 2>&1 ; then
			do_run=false
			error=1
		else
			sleep 1
		fi
	done
	trap - TERM INT
	return "${error}"
}

## set npm path
if [ -z "$NPM" ] ; then
  NPM=$(which npm)
fi

#if [[ -z "${JAVA_OPTS}" ]]; then
#  str=`file -L $JAVA | grep 64-bit`
#  if [ -n "$str" ]; then
#    JAVA_OPTS=" -Xms2048m -Xmx3072m -Xmn1024m -XX:SurvivorRatio=2 -XX:PermSize=96m -XX:MaxPermSize=256m -Xss256k -XX:-UseAdaptiveSizePolicy -XX:MaxTenuringThreshold=15 -XX:+DisableExplicitGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSCompactAtFullCollection -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:+HeapDumpOnOutOfMemoryError"
#  else
#    JAVA_OPTS=" -Xms1024m -Xmx1024m -XX:NewSize=256m -XX:MaxNewSize=256m -XX:MaxPermSize=128m "
#  fi
#  JAVA_OPTS=" -Xms1024m -Xmx1024m -XX:NewSize=256m -XX:MaxNewSize=256m -XX:MaxPermSize=128m "
#fi

echo "SPEC_PRJNAME: ${SPEC_PRJNAME}"
echo "PRJBASEDIR: ${PRJBASEDIR}"
echo "PRJDIR: ${PRJDIR}"
echo "PRJNAME: ${PRJNAME}"
echo "PRJPREFIX: ${PRJPREFIX}"
echo "BUILDENV: ${BUILDENV}"

if [ "${APPDEBUG}" = "debug" ]; then
  if [ "${BUILDENV}" = "dev" ]; then
      exec ${NPM} run dev
  else
      exec ${NPM} run dev:${BUILDENV}
  fi
else
  if [ "${BUILDENV}" = "prod" ]; then
      exec ${NPM} run build
  else
      exec ${NPM} run build:${BUILDENV}
  fi
  echo "==> START SUCCESSFUL ..."
  tail -f /dev/null &
  # wait TERM signal
  waitterm
fi
